<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	public function actions()
	{
		return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			));
	}
	
	public function actionIndex()
	{ 
	
		if(ApplicationSessions::run()->read('type') && ApplicationSessions::run()->read('id'))
		{
			$session_type = ApplicationSessions::run()->read('type');
			$this->redirect(ApplicationConfig::getURL('', $session_type, 'dashboard'));
		}
		else 
		{
			$this->redirect(ApplicationConfig::getURL('', 'user', 'login'));
		}
		
		return true;
	
	}
	
	/**
	 * This function is used for New User Register
	 * after Submitting valid form user will get redirect to Login form
	 * @access public
	 * @return void
	 * @author tushar
	 */
	public function actionRegister()
	{ 
		$arrCountryList = array();
		$arrStatesList = array();
		$arrCityList = array();
		$objUser=new User();
		$objContacts=new Contacts();
		$objUser->scenario = 'registration';
		$objContacts->scenario = 'contactinfo';
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($objUser);
		
		if(isset($_POST['User']) || isset($_POST['Contacts']))
		{ //echo "<pre>";
			//print_r($_POST);// exit;
			// for registration
			$objUser->attributes=isset($_POST['User']) ? $_POST['User'] : array();
			$objUser->copyaddress = isset($_POST['User']['copyaddress']) ? $_POST['User']['copyaddress'] : null ; 
			// for billing/contact
			$objContacts->attributes=isset($_POST['Contacts']) ? $_POST['Contacts'] : array();
			$objUser->salt=$objUser->generatesalt();
			$objUser->type=isset($_POST['User']['type'])?$_POST['User']['type']:null;
			if($objUser->validate() && $objContacts->validate())
			{
				if($objUser->save())
				{
					$objContacts->user_id = $objUser->id ;
					if($objContacts->save())
					{
						$this->redirect(ApplicationConfig::getURL('', 'user', 'login'));
					}
				}
			}
			
				if(isset($_POST['User']['country_id']))
				{
					$data = $arrParam['id'] = $_POST['User']['country_id'] ;
								$data = State::getList("STATE-LIST",$arrParam);
							foreach ($data as $states)
	              				$arrStatesList[$states->id]=$states->name;
	              			
				}	
				if(isset($_POST['User']['state_id']))
				{
					$data = $arrParam['id'] = $_POST['User']['state_id'] ;
								$data = City::getList("CITY-LIST",$arrParam);
							foreach ($data as $cities)
	              				$arrCityList[$cities->id]=$cities->name;
	              			
				}	
		}
		
		$arrCountryList = Country::getList('COUNTRY-LIST');
		$this->render('register',array(
		'objUser'=>$objUser,
		'objContacts'=>$objContacts,
		'arrCountryList'=>$arrCountryList,
		'arrStatesList'=>$arrStatesList,
		'arrCityList'=>$arrCityList,
		));
		//$this->render('register');
	}
	
	public function actiontest()
	{
		$this->render('test');
	}
	
	/*public function actionChangePassword_unuse()
	{
		//echo "<pre>";
		//$email = $ApplicationSessions::run()->read();
		$user_id = 13;
		$objDbUser = User::model()->findByPk((int)$user_id);
		//print_r($objDbUser->attributes);
		//echo "<br /><br /><br />";
		$model=new User();
		$model->scenario = 'changepass';
		if(isset($_POST['User']))
		{
			$model->attributes = $_POST['User'];
			$model->oldpassword = (isset($_POST['User']['oldpassword']) && $_POST['User']['oldpassword'] != null)?md5($_POST['User']['oldpassword'].$objDbUser->salt):'';
			$model->checkDbPassword = $objDbUser->password ;
			$model->password = (isset($_POST['User']['password']) && $_POST['User']['password'] != null)?md5($_POST['User']['password'].$objDbUser->salt):'';
			$model->password2 = (isset($_POST['User']['password2']) && $_POST['User']['password2'] != null)?md5($_POST['User']['password2'].$objDbUser->salt):'';
			echo "<br /> DBPassword   ".$model->checkDbPassword ;
			//print_r($model->oldpassword);
			echo "<br /> OldUser Enterd   ".$model->oldpassword ;
			echo "<br /> NEW User Enterd   ".$model->password ;
			echo "<br /> NEW Confirm Enterd   ".$model->password2 ;
			if($model->validate())
			{
				$model->updateByPk((int)$objDbUser->id,array('password'=>$model->password));
				echo "here after save new password it should get redirect to logging page"; exit;
			}
			else
			{
				$model->oldpassword = (isset($_POST['User']['oldpassword']) && $_POST['User']['oldpassword'] != null)?$_POST['User']['oldpassword']:'';
				$model->password = (isset($_POST['User']['password']) && $_POST['User']['password'] != null)?$_POST['User']['password']:'';
				$model->password2 = (isset($_POST['User']['password2']) && $_POST['User']['password2'] != null)?$_POST['User']['password2']:'';
			}
		}
		
		$this->render('changepass',array('model'=>$model));
	}*/

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * user login form.
	 * Here user can be client or company.
	 * @access public
	 * @return void
	 */
	public function actionLogin()
	{
	if(ApplicationSessions::run()->read('type') && ApplicationSessions::run()->read('id'))
		{
			$session_type = ApplicationSessions::run()->read('type');	
			$this->redirect(ApplicationConfig::getURL('', $session_type, 'dashboard'));
		}
		
		//echo 'here';
		$model = new LoginForm;
	
		if(isset($_POST['LoginForm']))
	    	{ 
	    		$model->attributes=$_POST['LoginForm'];
	    		//if($model->validate() && $model->login())
	    			//$this->redirect('index');
	    		if($model->validate())
	        	{
	        		$identity=new UserIdentity($_POST['LoginForm']['username'],$_POST['LoginForm']['password']);
	        		$error_code = $identity->authenticate();
	        	}
	        	
	    		if($error_code === "user_not_present")
					{
					 	//$this->redirect(Yii::app()->createUrl('users/register', array('email'=>$_POST['LoginForm']['username'])));
					 	$model->addError('password','Please check email and/or password');
					 	$model->password = '';	
					}
					elseif($error_code === "password_mismatch")
					{
						$model->addError('password','Password mismatch.');	
						$model->password = '';	
					}
					else
					{
						//$model->addError('password','Within error');
						$user = $error_code;
						//echo '<pre>';print_r($user);exit;
						//echo $user->email;exit;
						$identity->setIdentity($user);
						//echo '<pre>';print_r($identity);exit;
						$this->onLogin($user);
					}
	    	}
		$this->render('login',array('model'=>$model));
	}
	/**
	 * check user type(whether client or company).
	 * According to type redirect to appropriate dashboard(client or company).
	 * @access private
	 * @param take user object
	 * @return void
	 */
	private function onLogin($user)
  	{
  		if(isset($user))
  		{
  			if(ApplicationSessions::run()->read('type'))
  			{
	  			$type=ApplicationSessions::run()->read('type');	
	  			//echo $type;exit;
	  			if($type=="client")
	  				$this->redirect(Yii::app()->createUrl('client/dashboard'));
	  			elseif($type=="company")
	  				$this->redirect(Yii::app()->createUrl('company/dashboard'));
  			}
	  			
  		}
  	}
	
	/**
	 * Give Recover password form on clicking Forgot your password? link.
	 * check whether 'user' object is set or not,also check user 'status'.
	 * If user is 'active' create new resetpassword link and send that link on user email.
	 * @access public
	 * @return void
	 */
	public function actionRecover()
	{//exit("inside ForgotPassword action.");
		$model = new User;
		$model->scenario = 'reset';
		if(isset($_POST['User']))
	    	{
	    		$email = $_POST['User']['email'];
	    		//echo $email;exit;
	    		$time = time();
				$time = md5($time);
				//echo $time;exit;
				$user = User::model()->getModel('USER-EMAIL',array('email'=>$email));
				//echo $user->status;exit;
				if (isset($user) && $user->status == 'active')
				{
					$user->forgot_password_identifier = $time;
					$user->update(array('forgot_password_identifier'));
					//echo $user->forgot_password_identifier.'<br />';
					$url = Yii::app()->createAbsoluteUrl('/user/resetpassword/key/'.$user->forgot_password_identifier);
					//echo $url; exit; // mail this url to client
					//$headers="From: {'PDN'}\r\nReply-To: {$model->email}";
					//mail(Yii::app()->params['adminEmail'],'PDN Reset Password Link',"Open this $url",$headers);
					$to = "$user->email";
          			$subject = "Reset Password";
         			$message = 'Please click on the link to reset your password .'.$url;
         			$from = "Reset password <admin@vrpdn.com>";
          			$headers = "From:" . $from;
         			 mail($to,$subject,$message,$headers);
					Yii::app()->user->setFlash('success','Success :- Please check your Email!');
				}
				else
				{
					Yii::app()->user->setFlash('error','Error :- You are not active user!');
				}
	    	}
		$this->render('recover',array('model'=>$model));
	
	}
	/**
	 * Get 'key' value from 'resetpassword link'.
	 * check user entry against that key.
	 * If entry found redirect to ChangePasswordReset function.
	 * @access public
	 * @return void
	 */
	public function actionResetPassword()
	{
		$forgot_password_identifier = $_GET['key'];
		//echo $forgot_password_identifier.'<br />';
		$user = User::model()->getModel('USER-FORGOT_PASSWORD_IDENTIFIER',array('forgot_password_identifier'=>$forgot_password_identifier));
		//echo $user->email;exit;
		if($user)
		{
			$url = Yii::app()->createAbsoluteUrl('user/changePasswordReset/id/'.$user->id);
			$this->redirect("$url");
		}
		else
		{
			echo 'Error : Again reset your password!';exit;	
		}
	}
	/**
	 * Give Change password reset form.
	 * On successful change password
	 * @access public
	 * @return void
	 */
	public function actionChangePasswordReset()
	{
		$user_id = $_GET['id'];
		$model = $this->loadModel($user_id);
		if($model->forgot_password_identifier == '')
		exit("Error");
		$model->scenario = 'reset';
		
		if($_POST['User'])
			{
				//print_r($_POST['User']);
				$model->attributes = $_POST['User'];
				if($model->validate())
				{
					//exit("here");
					//$user->password = $time;
					$salt = User::model()->generateSalt();
					//echo $salt;
					$model->salt = $salt;
					$model->update(array('salt'));
					$model->password = md5($model->password.$salt);
					$model->update(array('password'));
					$model->forgot_password_identifier = '';
					$model->update(array('forgot_password_identifier'));
					$url = Yii::app()->createAbsoluteUrl('user/login');
					$this->redirect("$url");
				}
				
				
			}
		
		$this->render('changepasswordreset',array('model'=>$model,'id'=>$model->id));
	}
	/**
	 * Logout user
	 * unset defined session values
	 * redirect to user login page
	 * @access public
	 * @return void
	 */
	public function actionLogout()
	{
		ApplicationSessions::run()->delete('id');
		ApplicationSessions::run()->delete('email');
		ApplicationSessions::run()->delete('type');
		ApplicationSessions::run()->delete('first_name');
		ApplicationSessions::run()->delete('last_name');
		Yii::app()->user->logout();
		$this->redirect("login");
	}

	
//Ajax call function result suburb lists by city ids ..
	public function actionSearchValueStates_r()
	{ 
		//this function is using by business and propertydetails controller for suburb listing by seleting city
		$arrParam =array();
		if(isset($_POST['User']['country_id']))
		{	//print_r($_POST);
			$Term = $_POST['User']['country_id'] ;
			
			//echo $Term."%%%%----" ; 
			$case = "STATE-LIST";
			$prompt = "Select State";
		
			$arrParam['id'] = isset($Term)?$Term:null ;
			$data = State::getList($case,$arrParam);
				
		       $data = CHtml::listData($data,'id','name');
						    
		       echo CHtml::tag('option',array('value'=>''),$prompt,true);
			   foreach($data as $value=>$name)
			   {
			    	echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
			   }	
		}
		   Yii::app()->end();
	}
	
	public function actionSearchValueCities_r()
	{ 
		//this function is using by business and propertydetails controller for suburb listing by seleting city
		if(isset($_POST['User']['state_id']))
		{ print_r($_POST);
			$Term = $_POST['User']['state_id'] ;
			$case = "CITY-LIST";
			$prompt = "Select City";
		
			$arrParam['id'] = isset($Term)?$Term:null ;
			$data = City::getList($case,$arrParam);
				
		       $data = CHtml::listData($data,'id','name');
						    
		       echo CHtml::tag('option',array('value'=>''),$prompt,true);
			   foreach($data as $value=>$name)
			   {
			    	echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
			   }	
		} 
		   Yii::app()->end();
	}
	
public function actionSearchValueStates_c()
	{ 
		//this function is using by business and propertydetails controller for suburb listing by seleting city
		$arrParam =array();
		if(isset($_POST['Contacts']['country_id']))
		{	print_r($_POST);
			$Term = $_POST['Contacts']['country_id']  ;
			
			echo $Term."%%%%----" ; 
			$case = "STATE-LIST";
			$prompt = "Select State";
		
			$arrParam['id'] = isset($Term)?$Term:null ;
			$data = State::getList($case,$arrParam);
				
		       $data = CHtml::listData($data,'id','name');
						    
		       echo CHtml::tag('option',array('value'=>''),$prompt,true);
			   foreach($data as $value=>$name)
			   {
			    	echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
			   }	
		}
		   Yii::app()->end();
	}
	
	public function actionSearchValueCities_c()
	{ 
		//this function is using by business and propertydetails controller for suburb listing by seleting city
		if(isset($_POST['Contacts']['state_id']))
		{ print_r($_POST);
			$Term = $_POST['Contacts']['state_id'];
			$case = "CITY-LIST";
			$prompt = "Select City";
		
			$arrParam['id'] = isset($Term)?$Term:null ;
			$data = City::getList($case,$arrParam);
				
		       $data = CHtml::listData($data,'id','name');
						    
		       echo CHtml::tag('option',array('value'=>''),$prompt,true);
			   foreach($data as $value=>$name)
			   {
			    	echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
			   }	
		} 
		   Yii::app()->end();
	}
	
}
